<?php
/**
 * Created by PhpStorm.
 * User: 王世鹏
 * Date: 2018/3/6
 * Time: 15:34
 */

namespace app\index\controller;
use app\index\model\User as UserModel;
use think\Controller;
use think\Cookie;
class User extends Controller
{

    public function index()
    {
        $data = UserModel::paginate(1);
        $this->assign("data",$data);
        $this->assign("name","xigua");
        $this->view->engine->layout('layout','[__COMMENT__]');
        return $this->fetch();
    }























    public function add()
    {
       $user = new UserModel();
        if($user->allowField(true)->validate(true)->save(input("post."))){
            return "{$user->nickname} 编号:{$user->id}添加成功";
        }
        else{
            return $user->getError();
        }

    }

    public function read()
    {
        $user = UserModel::get(["id"=>2]);
        dump($user->username);
    }

    public function readAll()
    {
//        $users = UserModel::all(["username"=>"zan2"]);
//        $users = UserModel::all('1,2,3');
//        $users=UserModel::where('id','>',10)->select();
//        $users = UserModel::all(function($query){
//            $query->where('id','>',10);
//        });

//        foreach ($users as $u){
//            echo $u->username."<br/>";
//        }
    }


    public function update()
    {
        $user =UserModel::get(2);
        $user->password = "changed!!!";
        $user->save();
    }
    public function del()
    {
        $user =UserModel::get(1);
        if($user){
            $user->delete();
        }
    }
























    public function login()
    {
        $username =  input("post.username");
        $password = input("post.password");
        $db=db("user");
        if($db->where('username',$username)->where("password",$password)->count() ==1){
            setcookie("username",$username);
           return 1;
        }
        else{

            return 0;
        }


    }

    public function register()
    {
       $username =  input("post.username");
       $password = input("post.password");
       $db=db("user");
       if($db->where('username',$username)->count() !=0){
           return 2;
       }
       return $db->insert(['username'=>$username,'password'=>$password]);
    }


}